import { users } from "./index";
import { Socket } from "socket.io";
import {
    ON_USER_COME,
    ON_USER_FILE,
    ON_USER_MESSAGE
} from "./onName";

import {
    BROADCAST_USER_COME,
    BROADCAST_USER_FILE,
    BROADCAST_USER_LEAVE,
    BROADCAST_USER_MSG,
    BROADCAST_USER_ID,
} from "./emitName";

import {
    UserMsg,
    PicMsg,
    NicknameEnum
} from './type';


export default function(socket: Socket){
    // 用户断开连接
    socket.on("disconnect",() => {
        console.log('user disconnected!');
        var user = users[socket.id];
        delete users[socket.id];
        const userList = Object.keys(users);
        socket.broadcast.emit(BROADCAST_USER_LEAVE, { ...user, userList });
    });

    // 用户输入用户名提交后会触发这个事件 ------------------------------------------------->
    socket.on(ON_USER_COME,({nickname, userId}: {nickname: string; userId: number}) => {
        // 连接时将用户存起来
        let id = userId ? userId : Date.now();
        var code: NicknameEnum = NicknameEnum.NO_CHANGE;
        var oldName: string | number = "";      // oldName 只有在用户更改昵称才会被赋值
        if(!users[socket.id]){          // 新用户连接
            users[socket.id] = {
                nickname,
                userId: id
            }
            code = NicknameEnum.NEW_USER_COM;
        }else{
            // 用户更改昵称
            if(users[socket.id].nickname !== nickname){
                oldName = users[socket.id].nickname;
                users[socket.id].nickname = nickname;
                code = NicknameEnum.USER_RENAME;
            }
        }
        // 使用 io.emit 可以把信息推送给所有人
        // 而是用 socket.broadcast.emit 会向除某个发射套接字之外的所有人发送消息
        // 把 socket.id 也广播出去
        const userList = Object.values(users);
        socket.broadcast.emit(BROADCAST_USER_COME, { nickname: [nickname, oldName], code, userList });

        socket.emit(BROADCAST_USER_ID,{
            status: 1,
            msg: "OK",
            data: { nickname: [nickname, oldName], userId: id, code, userList },
        });
    });

    // 接收图片
    socket.on(ON_USER_FILE,(data: PicMsg) => {
        // 将接收到的图片广播出去
        const { nickname, message, filename } = data;
        socket.broadcast.emit(BROADCAST_USER_FILE, { message, nickname, filename  });
    });

    // 监听文本消息
    socket.on(ON_USER_MESSAGE,(data: UserMsg) => {
        const { nickname, message } = data;
        socket.broadcast.emit(BROADCAST_USER_MSG, { message, nickname });
    });
}